package com.niit.user_profile_center.controller;

import com.niit.user_profile_center.entity.Activity;
import com.niit.user_profile_center.entity.User;
import com.niit.user_profile_center.service.FollowService;
import com.niit.user_profile_center.service.UserService;


import com.niit.user_profile_center.utils.QiniuUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;   // 补充这一行
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.ArrayList;


@CrossOrigin(origins = "http://localhost:8080")

@RestController
@RequestMapping("api/user")
public class UserController {
    private final UserService userService;
    private final FollowService followService;
    private final QiniuUtil qiniuUtil;
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);


    public UserController(UserService userService, FollowService followService, QiniuUtil qiniuUtil) {
        this.userService = userService;
        this.followService = followService;
        this.qiniuUtil = qiniuUtil;
    }

    // 获取用户基本信息
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user == null) {
            System.out.println("用户不存在: ID=" + id);
            throw new RuntimeException("用户不存在");
        }
        user.setFollowerCount(userService.getFollowerCount(id));
        user.setFollowingCount(userService.getFollowingUsers(id).size());
        /// 打印用户基本信息
        System.out.println("获取用户基本信息: ID=" + user.getId() + ", Username=" + user.getUsername() +
                ", Followers=" + user.getFollowerCount() + ", Following=" + user.getFollowingCount());


        //return userService.getUserById(id);
        return user;
    }



    // 获取用户动态
    @GetMapping("/{id}/dynamics")
    public List<Activity> getActivity(@PathVariable Long id) {
        List<Activity> activities = userService.getUserActivity(id);
        // 打印用户动态信息
        System.out.println("获取用户动态: UserID=" + id + ", 动态数量=" + activities.size());
        return activities;
    }

    // 修改个人资料
    // 修改 updateUserProfile 方法，添加日志输出
    @PutMapping("/{id}/profile")
    public ResponseEntity<User> updateUserProfile(
            @PathVariable Long id,
            @RequestBody User user) {

        if (id == null || id <= 0) {
            return ResponseEntity.badRequest().build();
        }

        // 添加日志输出
        System.out.println("更新用户资料: ID=" + id);
        System.out.println("用户名: " + user.getUsername());
        System.out.println("昵称: " + user.getNickname());
        System.out.println("邮箱: " + user.getEmail());
        System.out.println("电话: " + user.getPhone());
        System.out.println("简介: " + user.getBio());

        // 处理逻辑
        // 这里应该调用UserService的updateProfile方法
        boolean result = userService.updateProfile(user);

        if (result) {
            System.out.println("用户资料更新成功: ID=" + id);
            return ResponseEntity.ok(user);
        } else {
            System.out.println("用户资料更新失败: ID=" + id);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // UserController.java
    @GetMapping("/search")
    public User searchUserByUsername(@RequestParam String username) {
        return userService.findUserByUsername(username);
    }
    // 用户关注操作
    @PostMapping("/follow")
    public ResponseEntity<?> follow(@RequestParam Long followerId, @RequestParam Long followingId) {
        // 添加参数验证
        if (followerId == null || followingId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }
        if (followerId.equals(followingId)) {
            return ResponseEntity.badRequest().body("不能关注自己");
        }

        try {
            int result = followService.follow(followerId, followingId);
            if (result == -1) {
                return ResponseEntity.status(HttpStatus.CONFLICT).body("已关注，无需重复操作");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("关注失败：" + e.getMessage());
        }
    }

    // 取消关注操作
    @PostMapping("/unfollow")
    public ResponseEntity<?> unfollow(@RequestParam Long followerId, @RequestParam Long followingId) {
        try {
            int result = followService.unfollow(followerId, followingId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("取消关注失败：" + e.getMessage());
        }
    }

    // 检查用户关注状态
    @GetMapping("/check")
    public Boolean checkFollowStatus(@RequestParam Long followerId, @RequestParam Long followingId) {
        return followService.checkFollowStatus(followerId, followingId);
    }

    // 获取用户关注列表（支持分页）
    @GetMapping("/{id}/following")
    public ResponseEntity<List<User>> getFollowingUsers(
            @PathVariable("id") Long id,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<User> followingUsers = followService.getFollowingUsers(id);
            int fromIndex = page * size;
            int toIndex = Math.min((page + 1) * size, followingUsers.size());
            if (fromIndex > followingUsers.size()) {
                return ResponseEntity.ok(new ArrayList<>());
            }
            return ResponseEntity.ok(followingUsers.subList(fromIndex, toIndex));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ArrayList<>());
        }
    }

    // 获取用户粉丝列表（支持分页）
    @GetMapping("/{id}/followers")
    public ResponseEntity<List<User>> getFollowers(
            @PathVariable("id") Long id,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<User> followers = followService.getFollowers(id);
            int fromIndex = page * size;
            int toIndex = Math.min((page + 1) * size, followers.size());
            if (fromIndex > followers.size()) {
                return ResponseEntity.ok(new ArrayList<>());
            }
            return ResponseEntity.ok(followers.subList(fromIndex, toIndex));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ArrayList<>());
        }
    }

    // 获取用户粉丝数
    @GetMapping("/{id}/followers/count")
    public ResponseEntity<Integer> getFollowersCount(@PathVariable("id") Long id) {
        try {
            if (id == null) {
                return ResponseEntity.badRequest().body(0);
            }
            int count = followService.getFollowers(id).size();
            System.out.println("获取用户粉丝数: UserID=" + id + ", 粉丝数=" + count);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            logger.error("获取粉丝数异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(0);
        }
    }

    // 获取用户关注数
    @GetMapping("/{id}/following/count")
    public ResponseEntity<Integer> getFollowingCount(@PathVariable("id") Long id) {
        try {
            if (id == null) {
                return ResponseEntity.badRequest().body(0);
            }
            int count = followService.getFollowingUsers(id).size();
            System.out.println("获取用户关注数: UserID=" + id + ", 关注数=" + count);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            logger.error("获取关注数异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(0);
        }
    }

    // 查询是否为好友
    @GetMapping("/isFriend")
    public ResponseEntity<Boolean> isFriend(@RequestParam Long userId, @RequestParam Long otherId) {
        boolean isFriend = followService.isFriend(userId, otherId);
        return ResponseEntity.ok(isFriend);
    }
    //七牛云上传
    @PostMapping("/{id}/avatar")
    public ResponseEntity<?> uploadAvatar(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("文件不能为空");
            }

            // 限制文件类型（可选）
            String contentType = file.getContentType();
            if (!"image/jpeg".equals(contentType) && !"image/png".equals(contentType) && !"image/jpg".equals(contentType)) {
                return ResponseEntity.badRequest().body("只支持 JPG、PNG 格式的图片");
            }

            // 限制文件大小（可选，例如限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest().body("文件大小不能超过5MB");
            }

            String avatarUrl = userService.updateAvatar(id, file);
            return ResponseEntity.ok(avatarUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败：" + e.getMessage());
        }
    }



}

